package initialize

import (
	"fmt"
	"github.com/google/uuid"
	"github.com/hashicorp/consul/api"
	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	"github.com/nacos-group/nacos-sdk-go/vo"
	"github.com/olivere/elastic/v7"
	"github.com/redis/go-redis/v9"
	"github.com/spf13/viper"
	"go.uber.org/zap"
	"google.golang.org/grpc"
	"google.golang.org/grpc/health"
	"google.golang.org/grpc/health/grpc_health_v1"
	"gopkg.in/yaml.v2"
	"log"
	"net"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"week_three/car_srv/common/global"
	"week_three/car_srv/logic"
	car_rpc "week_three/car_srv/proto"
)

func init() {
	InitZap()
	InitViper()
	InitNacos()
	InitRedis()
	InitEs()

}
func InitViper() {
	path := "./etc/deg.yaml"
	viper.SetConfigFile(path)
	err := viper.ReadInConfig()
	if err != nil {
		panic(err)
	}
	viper.Unmarshal(&global.NacosConfig)
	zap.S().Info("汽车项目启动：：：：")
}
func InitNacos() {
	// 创建clientConfig
	clientConfig := constant.ClientConfig{
		NamespaceId:         global.NacosConfig.NamespaceId, // 如果需要支持多namespace，我们可以场景多个client,它们有不同的NamespaceId。当namespace是public时，此处填空字符串。
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              "/tmp/nacos/log",
		CacheDir:            "/tmp/nacos/cache",
		LogLevel:            "debug",
	}
	serverConfigs := []constant.ServerConfig{
		{
			IpAddr: global.NacosConfig.Host,
			Port:   uint64(global.NacosConfig.Port),
		},
	}
	// 创建动态配置客户端的另一种方式 (推荐)
	configClient, err := clients.NewConfigClient(
		vo.NacosClientParam{
			ClientConfig:  &clientConfig,
			ServerConfigs: serverConfigs,
		},
	)
	if err != nil {
		panic(err)
	}
	content, err := configClient.GetConfig(vo.ConfigParam{
		DataId: global.NacosConfig.DataId,
		Group:  global.NacosConfig.Group,
	})
	if err != nil {
		panic(err)
	}
	yaml.Unmarshal([]byte(content), &global.UserConfig)
}
func InitGrpc() {
	GrpcServer := grpc.NewServer()
	Server := &logic.CarRpc{}
	car_rpc.RegisterCarServer(GrpcServer, Server)
	grpc_health_v1.RegisterHealthServer(GrpcServer, health.NewServer())
	log.Println(global.UserConfig.UserConf.Host, global.UserConfig.UserConf.Port, "....")
	listen, err := net.Listen("tcp", fmt.Sprintf("%s:%d", global.UserConfig.UserConf.Host, global.UserConfig.UserConf.Port))
	if err != nil {
		panic(err)
	}
	go func() {
		if err = GrpcServer.Serve(listen); err != nil && err != http.ErrAbortHandler {
			panic(err)
		}
	}()
	InitConsul()
	SigChan := make(chan os.Signal, 1)
	signal.Notify(SigChan, syscall.SIGTERM, syscall.SIGINT)
	<-SigChan
	global.ConsulClient.Agent().ServiceDeregister(global.UserConfig.ConsulConf.Id)
}
func InitConsul() {
	var err error
	global.ConsulClient, err = api.NewClient(api.DefaultConfig())
	if err != nil {
		panic(err)
	}
	global.UserConfig.ConsulConf.Id = uuid.NewString()
	err = global.ConsulClient.Agent().ServiceRegister(&api.AgentServiceRegistration{
		ID:      global.UserConfig.ConsulConf.Id,
		Name:    global.UserConfig.ConsulConf.Name,
		Tags:    global.UserConfig.ConsulConf.Tags,
		Port:    global.UserConfig.UserConf.Port,
		Address: global.UserConfig.UserConf.Host,
	})
	if err != nil {
		panic(err)
	}
}
func InitRedis() {
	fmt.Println(global.UserConfig.RedisConf, "dd")
	global.RedisClient = redis.NewClient(&redis.Options{
		Addr: fmt.Sprintf("%s:%d", global.UserConfig.RedisConf.Host, global.UserConfig.RedisConf.Port),
		DB:   global.UserConfig.RedisConf.Db, // use default DB
	})
}
func InitEs() {
	var (
		err error
		dsn = fmt.Sprintf("http://%s:%d", global.UserConfig.EsConf.Host, global.UserConfig.EsConf.Port)
	)

	global.EsClient, err = elastic.NewClient(elastic.SetURL(dsn), elastic.SetSniff(false))
	if err != nil {
		panic(err)
	}
}
func InitZap() {
	config := zap.NewDevelopmentConfig()
	config.OutputPaths = []string{
		"./log/user.log",
		"stderr",
		"stdout",
	}
	logger, _ := config.Build()
	zap.ReplaceGlobals(logger)
}
